import $store from '@/store'
import uniApi from '@/util/uniApi'

/**
 * 获取页面栈历史记录、当前页面路径及参数
 */
export function getCurrentPage() {
	// eslint-disable-next-line no-undef
	const pages = getCurrentPages()
	const currentPage = pages[pages.length - 1]
	if (!currentPage) {
		return { pages }
	}

	const path = `/${currentPage.route}`
	const options = currentPage.options || {}

	// eslint-disable-next-line no-use-before-define
	const queryStr = queryStringify(options)

	let fullPath = path
	if (queryStr) {
		fullPath += `?${queryStr}`
	}

	// #ifdef APP-PLUS
	fullPath = currentPage.$page.fullPath
	// #endif

	return { pages, options, path, fullPath }
}

/**
 * 将键值对形式参数格式化为查询参数字符串
 * @param {object} query 键值对形式参数
 * @param {boolean} isFilterEmpty 是否过滤空值
 * @returns {string} 返回带问号的url查询参数字符串
 */
export function queryStringify(query, isFilterEmpty = true) {
	const queryArr = []
	Object.keys(query).forEach((key) => {
		const value = query[key]
		if (isFilterEmpty) {
			value && queryArr.push(`${key}=${value}`)
		} else {
			queryArr.push(`${key}=${value}`)
		}
	})
	return queryArr.join('&')
}

/**
 * 解析url查询参数
 * @param {string} query 不带问号的查询参数字符串
 * @returns {object} 返回对象形式
 */
export function queryParse(query) {
	const result = {}
	if (query) {
		decodeURIComponent(query)
			.split('&')
			.map((v) => v.split('='))
			.forEach(([key, value]) => {
				result[key] = value
			})
	}
	return result
}

/**
 * 未登录跳转登录页 注意使用 async await 或者 .then() 调用
 * @param {boolean} tag 是否是tab页
 */
export function checkLogin(tag = false) {
	return new Promise((resolve, reject) => {
		let url = '/pages/login/index'
		// #ifdef APP-PLUS
		url = '/pages/login/index?source=2'
		// #endif
		if (!$store('user').userInfo.mobile) {

			let {fullPath = ''} = getCurrentPage()
			$store('app').setRelaunchUrl(fullPath)

			tag ? uniApi.redirect(url) : uniApi.pageNav({url})
			reject()
		} else {
			resolve()
		}
	})
}
